<template>
  <div>
    <Header/>
    <div class="login-container">
      <div class="login-box">
        <h2 class="login-title">账号登录</h2>

        <div class="login-tabs">
          <span :class="['tab-item', { active: loginType === 'password' }]"
                @click="loginType = 'password'">密码登录</span>
          <span :class="['tab-item', { active: loginType === 'sms' }]"
                @click="loginType = 'sms'">短信登录</span>
        </div>

        <div class="login-form">
          <!-- 用户名输入 -->
          <div class="form-item" v-if="loginType === 'password'">
            <input type="text"
                   v-model="form.username"
                   placeholder="请输入用户名"
                   @blur="validateUsername">
            <span class="error-tip" v-if="errors.username">{{ errors.username }}</span>
          </div>

          <!-- 密码登录 -->
          <div class="form-item" v-if="loginType === 'password'">
            <input :type="showPassword ? 'text' : 'password'"
                   v-model="form.password"
                   placeholder="请输入密码">
            <span class="toggle-password" @click="showPassword = !showPassword">
              {{ showPassword ? '隐藏' : '显示' }}
            </span>
            <span class="error-tip" v-if="errors.password">{{ errors.password }}</span>
          </div>




          <!-- 手机号输入 -->
          <div class="form-item" v-if="loginType ==='sms'">
            <input type="text"
                   v-model="form.phone"
                   placeholder="请输入手机号"
                   @blur="validatePhone">
            <span class="error-tip" v-if="errors.phone">{{ errors.phone }}</span>
          </div>

          <!-- 短信验证码登录 -->
          <div class="form-item sms-code" v-if="loginType === 'sms'">
            <input type="text"
                   v-model="form.smsCode"
                   placeholder="请输入验证码">
            <button class="send-code-btn"
                    :disabled="countdown > 0"
                    @click="sendSmsCode">
              {{ countdown > 0 ? `${countdown}秒后重新发送` : '发送验证码' }}
            </button>
            <span class="error-tip" v-if="errors.smsCode">{{ errors.smsCode }}</span>
          </div>

          <!-- 记住密码选项 -->
          <div class="form-item remember-row">
            <label class="remember-pwd">
              <input type="checkbox" v-model="form.remember">
              <span>记住密码</span>
            </label>
            <a href="#" class="forget-pwd">忘记密码？</a>
          </div>

          <!-- 登录按钮 -->
          <button class="login-btn" @click="handleLogin">登录</button>

          <!-- 其他登录方式 -->
          <div class="other-login">
            <div class="divider">
              <span>其他登录方式</span>
            </div>
            <div class="social-login">
              <a href="#" class="social-item wechat">
                <i class="iconfont icon-wechat"></i>
              </a>
              <a href="#" class="social-item qq">
                <i class="iconfont icon-qq"></i>
              </a>
            </div>
          </div>

          <!-- 注册入口 -->
          <div class="register-link">
            还没有账号？<a href="#" @click.prevent="goToRegister">立即注册</a>
          </div>
        </div>
      </div>
    </div>
  </div>
</template>

<script setup>
import {ref, reactive} from 'vue'
import {useRouter} from 'vue-router'
import axios from 'axios'
import Header from '../components/Header.vue'

const router = useRouter()
const loginType = ref('password') // 登录方式：password/sms
const showPassword = ref(false)
const countdown = ref(0)

// 表单数据
const form = reactive({
  username: '',  // 修改为username
  password: '',
  smsCode: '',
  phone:'',
  remember: false
})

// 表单错误信息
const errors = reactive({
  username: '',  // 修改为username
  password: '',
  smsCode: '',
  phone:''
})


// 验证用户名登录函数：
function validateUsername(){
  //还是先判断是否为空
  if (!form.username){
    errors.username = '用户名不能为空'  // 这个就是你鼠标离开了输入框给你提示的东西
  }else{
    errors.username = ''   //输东西了不算错误就不用提示错误信息，什么都不改动
  }

  return !errors.username  //返回true就是写了东西，返回false就是没东西-->所以他会根据上面的验证结果自动返回t或者f
  // 算是一种固定的写法
}

//用户名登录
function handleLogin() {

  //写在最前-->因为两个登陆都是登陆，都要用到这个方法，区分的话直接进行登录类型判断
  if (loginType.value === 'password') {

    //密码登录
    // 1.先验证用户名
    if (!validateUsername()) return  //如果上面的验证结果不为t，就说明没写，就不让登录

    if (!form.password) {    //如果登陆方式为密码用户名登陆 且 密码没写(!代表not，取反)
      //你就要进行提醒
      errors.password = '密码不能为空'
      return   //如果密码没写，就不让登录，直接结束函数
    }
  }else{
    if (!validatePhone()) return;
    if (!form.smsCode){
      errors.smsCode = '验证码不能为空'
      return
    }
    }


  if (loginType.value === 'password') {
    //2.我就开始调请求，我就需要从后端向我返回验证查询结果了
    //这里是else的情况函数
    try {
      axios.post(`http://localhost:8000/api/login/`, {username: form.username, password: form.password}).then(res => {
        // 3. 如果验证成功，跳转到首页
        console.log(res)
        if (res.data.code === 1){   //判断后端是否验证成功的信息就是code=1
          alert('登录成功')
          router.push('/')
          // 4. 如果记住密码，就把用户名和密码存到浏览器的localStorage中,储存你前端登陆成功设置的所有东西；
          // 如果没点记住密码，那就存储在session中
          // remember: false
          if (form.remember){
            localStorage.setItem('username',res.data.data.username)
            localStorage.setItem('user_id',res.data.data.user_id)
            localStorage.setItem('token',res.data.data.token)
            localStorage.setItem('refresh_token',res.data.data.refresh)
          }else{
            sessionStorage.setItem('username',res.data.data.username)
            sessionStorage.setItem('user_id',res.data.data.user_id)
            sessionStorage.setItem('token',res.data.data.token)
            sessionStorage.setItem('refresh_token',res.data.data.refresh)
          }

        }else{
          alert('登陆失败')
        }
      })
    }catch (err){
      console.log(err)
      if (err.response && err.response.data){  //如果有返回了错误信息
        const error = err.response.data.msg || '登录失败'   //我就用变量接受错误信息，没有就提示默认值的公路失败(||默认值语法)
        if (loginType.value === 'password'){   //如果是密码登录，就把错误信息赋值给 密码登录的错误提示信息变量errors.password
          errors.password = error
        }
      }
    }



    //else是验证码登陆
  }else {
    try{
      axios.post(`http://localhost:8000/api/sent_login/`,{'phone':form.phone,'code':form.smsCode}).then(res=>{
        console.log(res)
        if (res.data.code === 1){
          alert('登录成功')
          router.push('/')
          //存储token信息
          if (form.remember){
            localStorage.setItem('username',res.data.data.username)
            localStorage.setItem('user_id',res.data.data.user_id)
            localStorage.setItem('token',res.data.data.token)
            localStorage.setItem('refresh_token',res.data.data.refresh)
          }else {
            sessionStorage.setItem('username',res.data.data.username)
            sessionStorage.setItem('user_id',res.data.data.user_id)
            sessionStorage.setItem('token',res.data.data.token)
            sessionStorage.setItem('refresh_token',res.data.data.refresh)
          }

        }else {
          alert(res.data.msg)

        }
      })
    }catch (err){
      alert('登录失败')
    }
  }
}




const phoneRegex = /^1[3-9]\d{9}$/
//短信验证码登录：
function validatePhone(){
  if (!form.phone){
    errors.phone = '手机号不能为空'
  } else if (!phoneRegex.test(form.phone)){  //正则
    errors.phone = '手机号格式不正确'
  }else {
    errors.phone = ''
    return true
  }

  return false
}

//发送验证码
function sendSmsCode(){
  if (!validatePhone()) return
  //验证成功了就发送验证码
  axios.post(`http://localhost:8000/api/send/`,{'phone':form.phone}).then(res=>{
    console.log(res)
    if (res.data.code === 1){
      alert('验证码发送成功')
      countdown.value = 60  //但即使60秒


      //定义一个定时器，每隔一秒钟就减一秒，直到倒计时为0，然后清除定时器
      const timer = setInterval(
          ()=>{
            countdown.value--  //每隔一秒钟就减一秒
            if (countdown.value <= 0){
              clearInterval(timer)
            }
          },1000)  //每隔一秒钟就显示，1000毫秒(单位是毫秒)


    }else {
      alert(res.data.msg)
    }
  })
}


function goToRegister(){
  router.push('/register')
}










</script>

<style scoped>
.login-container {
  min-height: calc(100vh - 60px); /* 减去header的高度 */
  margin-top: 60px; /* header的高度 */
  display: flex;
  justify-content: center;
  align-items: center;
  background: #f5f5f5;
}

.login-box {
  width: 400px;
  padding: 40px;
  background: white;
  border-radius: 8px;
  box-shadow: 0 2px 12px rgba(0, 0, 0, 0.1);
}

.login-title {
  text-align: center;
  font-size: 24px;
  color: #333;
  margin-bottom: 30px;
}

.login-tabs {
  display: flex;
  margin-bottom: 24px;
  border-bottom: 1px solid #e8e8e8;
}

.tab-item {
  flex: 1;
  text-align: center;
  padding: 12px 0;
  font-size: 16px;
  color: #666;
  cursor: pointer;
  position: relative;
}

.tab-item.active {
  color: #ff6b00;
}

.tab-item.active::after {
  content: '';
  position: absolute;
  bottom: -1px;
  left: 50%;
  transform: translateX(-50%);
  width: 40%;
  height: 2px;
  background: #ff6b00;
}

.form-item {
  margin-bottom: 20px;
  position: relative;
}

.form-item input {
  width: 100%;
  padding: 12px;
  border: 1px solid #dcdfe6;
  border-radius: 4px;
  font-size: 14px;
  transition: all 0.3s;
}

.form-item input:focus {
  border-color: #ff6b00;
  outline: none;
}

.error-tip {
  position: absolute;
  left: 0;
  bottom: -20px;
  color: #f56c6c;
  font-size: 12px;
}

.toggle-password {
  position: absolute;
  right: 10px;
  top: 50%;
  transform: translateY(-50%);
  color: #909399;
  cursor: pointer;
  font-size: 14px;
}

.sms-code {
  display: flex;
  gap: 10px;
}

.sms-code input {
  flex: 1;
}

.send-code-btn {
  width: 120px;
  padding: 0 15px;
  border: 1px solid #ff6b00;
  border-radius: 4px;
  background: white;
  color: #ff6b00;
  cursor: pointer;
  white-space: nowrap;
}

.send-code-btn:disabled {
  border-color: #dcdfe6;
  color: #909399;
  cursor: not-allowed;
}

.remember-row {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.remember-pwd {
  display: flex;
  align-items: center;
  gap: 6px;
  color: #606266;
  cursor: pointer;
}

.forget-pwd {
  color: #909399;
  text-decoration: none;
}

.forget-pwd:hover {
  color: #ff6b00;
}

.login-btn {
  width: 100%;
  padding: 12px;
  background: #ff6b00;
  color: white;
  border: none;
  border-radius: 4px;
  font-size: 16px;
  cursor: pointer;
  transition: all 0.3s;
}

.login-btn:hover {
  background: #ff8533;
}

.other-login {
  margin-top: 24px;
}

.divider {
  display: flex;
  align-items: center;
  color: #909399;
  font-size: 14px;
  margin: 20px 0;
}

.divider::before,
.divider::after {
  content: '';
  flex: 1;
  height: 1px;
  background: #dcdfe6;
  margin: 0 16px;
}

.social-login {
  display: flex;
  justify-content: center;
  gap: 30px;
}

.social-item {
  width: 40px;
  height: 40px;
  border-radius: 50%;
  display: flex;
  align-items: center;
  justify-content: center;
  color: white;
  text-decoration: none;
  transition: all 0.3s;
}

.social-item.wechat {
  background: #07c160;
}

.social-item.qq {
  background: #12b7f5;
}

.social-item:hover {
  transform: translateY(-2px);
}

.register-link {
  margin-top: 20px;
  text-align: center;
  color: #606266;
}

.register-link a {
  color: #ff6b00;
  text-decoration: none;
}

.register-link a:hover {
  text-decoration: underline;
}
</style>